from marshmallow import Schema, fields, validate, validates, ValidationError, post_load
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from datetime import datetime
import sys
sys.path.append("/")
from app.extensions import db
from app.models.user import User, Department




class UserSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = User
        load_instance = True
        sqla_session = db.session
        exclude = ("password_hash",)
        dump_only = ("id", "created_at")
        include_relationships = True  # 关键添加

    email = fields.String(
        required=True,
        validate=validate.Email(error="Not a valid email address")  # 只保留格式验证
    )
    password = fields.String(required=True, load_only=True, validate=validate.Length(min=6))
    roles = fields.List(fields.String(), dump_only=True)

    department = fields.String(required=True)

    @validates("username")
    def validate_username(self, value, **_):
        if User.query.filter_by(username=value).first():
            raise ValidationError("Username already exists")

    @validates('email')
    def validate_email_unique(self, value, **_):
        """处理唯一性验证"""
        if User.query.filter_by(email=value).first():
            raise ValidationError("Email already exists")

    @post_load
    def convert_department(self, data, **kwargs):
        # 将部门名称转换为部门实例
        if 'department' in data:
            dept_name = data['department']
            if isinstance(dept_name, str):
                dept = Department.query.filter_by(name=dept_name).first()
                if not dept:
                    raise ValidationError(f"Department '{dept_name}' not found")
                data['department'] = dept
        return data


class UserUpdateSchema(SQLAlchemyAutoSchema):

    email = fields.String(
        required=False,
        validate=validate.Email(error="Not a valid email address")  # 只保留格式验证
    )
    username = fields.String(
        required=False
    )

    @validates("username")
    def validate_username(self, value, **_):
        if User.query.filter_by(username=value).first():
            raise ValidationError("Username already exists")

    @validates('email')
    def validate_email_unique(self, value, **_):
        """处理唯一性验证"""
        if User.query.filter_by(email=value).first():
            raise ValidationError("Email already exists")

class LoginSchema(Schema):
    username = fields.String(required=True)
    password = fields.String(required=True)


class PasswordResetSchema(Schema):
    new_password = fields.String(required=True, validate=validate.Length(min=6))
    token = fields.String(required=True)


class AdminUserUpdateSchema(SQLAlchemyAutoSchema):
    is_active = fields.Boolean(
        required=False
    )
    is_admin = fields.Boolean(
        required=False
    )


class ManagerChangeUserRoleSchema(SQLAlchemyAutoSchema):
    roles = fields.List(fields.String(required=True))

class ManagerChangeUserDepartmentSchema(SQLAlchemyAutoSchema):
    department = fields.String(required=True)



# 初始化schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)
user_update_schema = UserUpdateSchema()
login_schema = LoginSchema()
password_reset_schema = PasswordResetSchema()
admin_user_update_schema = AdminUserUpdateSchema()
manager_change_user_role_schema = ManagerChangeUserRoleSchema()
manager_change_user_department_schema = ManagerChangeUserDepartmentSchema()